package html;

import java.util.LinkedHashMap;
import java.util.Map;

import node.Node;

import com.google.common.base.Joiner;

/**
 * Created by thormentor on 29-04-2014.
 */
public class HtmlElement extends Node {
	private static final String CLOSED_PATTERN = "<%s%s/>";
	private static final String OPEN_PATTERN = "<%s%s>";

	private final String tagName = getClass().getSimpleName().toLowerCase();
	private final Map<String, HtmlAttribute> attributes = new LinkedHashMap<>();

	@Override
	protected String getBegin() {
		return String.format(
				isClosed() ? CLOSED_PATTERN :OPEN_PATTERN,
						tagName,
						attributeString()
				);
	}

	public HtmlElement attribute(final String name, final String value){
		attributes.put(name, new HtmlAttribute(name, value));
		return this;
	}

	private String attributeString() {
		return attributes.isEmpty() ? "" : " " + Joiner.on(" ").join(attributes.values());
	}

	@Override
	protected String getEnd() {
		return String.format("</%s>", tagName);
	}

	public HtmlElement addClass(final String className) {
		attribute("class", className);
		return this;
	}
}
